import sys
from PySide6.QtWidgets import (QApplication, QDialog, QTableWidget, QTableWidgetItem, 
                             QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, 
                             QWidget, QMessageBox, QComboBox, QHeaderView)
from PySide6.QtCore import Qt

from gui.utils.api import API

class TableWidget_Datamanager(QDialog):
    def __init__(self,api):
        super().__init__()
        self.setWindowTitle("数据分页表格管理系统")
        self.resize(1000, 600)
        self.api:API = api
        self.api.request_result.connect(self.api_success_response)
        self.api.request_error.connect(self.api_success_response)
        self.data = self.generate_sample_data(100)  # 生成100条示例数据
        self.current_page = 1
        self.items_per_page = 10
        self.total_pages = len(self.data) // self.items_per_page + (1 if len(self.data) % self.items_per_page > 0 else 0)
        self.filtered_data = self.data.copy()
        
        # 创建UI
        self.setup_ui()
        self.update_table()
    
    def generate_sample_data(self, count):
        """生成示例数据"""
        data = []
        for i in range(1, count + 1):
            data.append({
                "id": i,
                "name": f"用户{i}",
                "age": 20 + (i % 30),
                "gender": "男" if i % 2 == 0 else "女",
                "email": f"user{i}@example.com",
                "phone": f"138001380{i:02d}"
            })
        return data
    
    def setup_ui(self):
        """设置用户界面"""
        # 创建主布局
        main_layout = QVBoxLayout()
        
        # 搜索区域
        search_layout = QHBoxLayout()
        
        # 搜索字段选择
        self.search_field = QComboBox()
        self.search_field.addItems(["姓名", "邮箱", "电话"])
        
        # 搜索框
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入搜索内容...")
        self.search_input.returnPressed.connect(self.search_data)
        
        # 搜索按钮
        self.search_button = QPushButton("搜索")
        self.search_button.clicked.connect(self.search_data)
        
        # 添加到搜索布局
        search_layout.addWidget(QLabel("搜索:"))
        search_layout.addWidget(self.search_field)
        search_layout.addWidget(self.search_input)
        search_layout.addWidget(self.search_button)
        search_layout.addStretch()
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels(["ID", "姓名", "年龄", "性别", "邮箱", "电话"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        
        # 分页控制
        pagination_layout = QHBoxLayout()
        
        # 上一页按钮
        self.prev_button = QPushButton("上一页")
        self.prev_button.clicked.connect(self.prev_page)
        
        # 当前页码显示
        self.page_label = QLabel(f"第 {self.current_page} 页，共 {self.total_pages} 页")
        
        # 下一页按钮
        self.next_button = QPushButton("下一页")
        self.next_button.clicked.connect(self.next_page)
        
        # 每页显示数量
        self.items_per_page_combo = QComboBox()
        self.items_per_page_combo.addItems(["10", "20", "50", "100"])
        self.items_per_page_combo.setCurrentText(str(self.items_per_page))
        self.items_per_page_combo.currentTextChanged.connect(self.change_items_per_page)
        
        # 添加到分页布局
        pagination_layout.addWidget(self.prev_button)
        pagination_layout.addWidget(self.page_label)
        pagination_layout.addWidget(self.next_button)
        pagination_layout.addStretch()
        pagination_layout.addWidget(QLabel("每页显示:"))
        pagination_layout.addWidget(self.items_per_page_combo)
        
        # 添加所有布局到主布局
        main_layout.addLayout(search_layout)
        main_layout.addWidget(self.table)
        main_layout.addLayout(pagination_layout)
        
        # 设置中央部件
        central_widget = QWidget(self)
        central_widget.setLayout(main_layout)
        
        # self.setCentralWidget(central_widget)
        
        # 更新分页按钮状态
        self.update_pagination_buttons()
    
    def update_table(self):
        """更新表格显示"""
        # 计算当前页的数据范围
        start_idx = (self.current_page - 1) * self.items_per_page
        end_idx = min(start_idx + self.items_per_page, len(self.filtered_data))
        current_page_data = self.filtered_data[start_idx:end_idx]
        
        # 清空表格
        self.table.setRowCount(0)
        
        # 填充表格
        for row, item in enumerate(current_page_data):
            self.table.insertRow(row)
            self.table.setItem(row, 0, QTableWidgetItem(str(item["id"])))
            self.table.setItem(row, 1, QTableWidgetItem(item["name"]))
            self.table.setItem(row, 2, QTableWidgetItem(str(item["age"])))
            self.table.setItem(row, 3, QTableWidgetItem(item["gender"]))
            self.table.setItem(row, 4, QTableWidgetItem(item["email"]))
            self.table.setItem(row, 5, QTableWidgetItem(item["phone"]))
        
        # 更新分页信息
        self.total_pages = len(self.filtered_data) // self.items_per_page + (1 if len(self.filtered_data) % self.items_per_page > 0 else 0)
        self.page_label.setText(f"第 {self.current_page} 页，共 {self.total_pages} 页")
        
        # 更新分页按钮状态
        self.update_pagination_buttons()
    
    def update_pagination_buttons(self):
        """更新分页按钮状态"""
        self.prev_button.setEnabled(self.current_page > 1)
        self.next_button.setEnabled(self.current_page < self.total_pages)
    
    def prev_page(self):
        """上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.update_table()
    
    def next_page(self):
        """下一页"""
        if self.current_page < self.total_pages:
            self.current_page += 1
            self.update_table()
    
    def change_items_per_page(self, text):
        """更改每页显示数量"""
        self.items_per_page = int(text)
        self.current_page = 1  # 重置到第一页
        self.update_table()
    
    def search_data(self):
        """搜索数据"""
        search_text = self.search_input.text().strip().lower()
        field = self.search_field.currentText()
        
        if not search_text:
            # 如果搜索框为空，显示全部数据
            self.filtered_data = self.data.copy()
        else:
            # 根据选择的字段进行过滤
            if field == "姓名":
                self.filtered_data = [item for item in self.data if search_text in item["name"].lower()]
            elif field == "邮箱":
                self.filtered_data = [item for item in self.data if search_text in item["email"].lower()]
            elif field == "电话":
                self.filtered_data = [item for item in self.data if search_text in item["phone"].lower()]
        
        # 重置到第一页
        self.current_page = 1
        
        # 更新表格
        self.update_table()
        
        # 显示搜索结果信息
        if search_text:
            QMessageBox.information(self, "搜索结果", f"找到 {len(self.filtered_data)} 条匹配记录")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TableWidget_Datamanager()
    window.show()
    sys.exit(app.exec())